
package com.tsingxiao.codegenerate.api.controller;

import com.tsingxiao.codegenerate.common.dto.ResultDto;
import com.tsingxiao.codegenerate.common.exception.BusinessException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 异常处理
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerResolver {

    /**
     * 全局异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDto<String> handleException(Exception e) {
        log.error("系统异常", e);
        return new ResultDto<>(ResultDto.ResultEnum.FAIL.getCode(), e.getLocalizedMessage());
    }

    /**
     * 业务异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDto<String> handleBusinessException(BusinessException e) {
        log.error("业务异常", e);
        return new ResultDto<>(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultDto<String> handleBindException(BindException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.error("参数异常, {}", fieldErrors.get(0).getDefaultMessage());
        return new ResultDto<>(ResultDto.ResultEnum.FAIL.getCode(), fieldErrors.get(0).getDefaultMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultDto<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error("参数异常, {}", msg);
        return new ResultDto<>(ResultDto.ResultEnum.FAIL.getCode(), msg);
    }

}
